package com.ropa.java.googleauthenticate.rest;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;

@RestController
public class AuthController {

    @Autowired
    private GoogleAuthenticator googleAuthenticator;

    @GetMapping("qrcode")
    @SneakyThrows
    public void getQrCode(String username, HttpServletResponse response){
        GoogleAuthenticatorKey credentials = googleAuthenticator.createCredentials(username);
        String otpAuthTotpURL = GoogleAuthenticatorQRGenerator.getOtpAuthTotpURL(null, username, credentials);

        BitMatrix bitMatrix = new QRCodeWriter().encode(otpAuthTotpURL, BarcodeFormat.QR_CODE, 300, 300);
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, new MatrixToImageConfig(Color.BLACK.getRGB(), Color.WHITE.getRGB()));
        ImageIO.write(bufferedImage, "png", response.getOutputStream());
    }


    @PostMapping("auth")
    public boolean authenticate(String username, Integer gaCode){
        boolean authorize = googleAuthenticator.authorizeUser(username, gaCode);
        return authorize;
    }

}
